package com.woniuxy.classdeans.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.classdeans.configuration.FileConfig;
import com.woniuxy.classdeans.service.UploadingService;
import com.woniuxy.commons.entity.ResponseResult;
import com.woniuxy.commons.entity.wyh.Knowledgepoint;
import com.woniuxy.commons.enums.KnowledgepointEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.woniuxy.commons.enums.KnowledgepointEnum.*;
import static com.woniuxy.commons.utils.FilesUpload.analysisExcel;

/* *
 * @Author weizihan
 * @Date 2020/7/17 2020/7/17
 * @Description 知识点文档上传
 * @Since version-1.0
 */
@RestController
@RequestMapping("/uploading")
public class UploadingController {
    @Autowired
    private FileConfig fileConfig;  //注入file加载路径
    @Autowired
    private UploadingService uploadingService;


    @RequestMapping("/files")
    public ResponseResult<Map<String,Object>> fileUpload(@RequestParam("file")MultipartFile multipartFile, HttpServletRequest request)
            throws Exception{
        //获取名字
        String originalFilename = multipartFile.getOriginalFilename();
        //创建一个list存储数据
        List<Knowledgepoint> listKnowledgepoint = new ArrayList<Knowledgepoint>();
        //文件存储的本地硬盘目录
        String localhostFilePatn = fileConfig.getUploadFilePatn();
        //配置文件名字
        String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        //存储到本地磁盘中
        File file = new File(localhostFilePatn);
        if(!file.exists())
                file.mkdirs();
        //存放文件地址
        localhostFilePatn = file.getAbsolutePath()+File.separator+fileName;
        //写入
        File location = new File(localhostFilePatn);
        multipartFile.transferTo(location);

        Map<String, Object> map = analysisExcel(localhostFilePatn);
       //通过反射获取最后的key
        Field tail = map.getClass().getDeclaredField("tail");
        tail.setAccessible(true);
        Map.Entry<String,Object> entry = (Map.Entry<String, Object>) tail.get(map);
        String key = entry.getKey();
        String[] keys = key.split(",");
        String s = keys[1];
        //上传时查询有没有传入过的知识点，保证知识点的唯一性
        List<Knowledgepoint> kdnameAll = uploadingService.selecKdnameAll();
       // System.out.println(keys[1]+".........."+s);
        for (int i = 1 ; i <= Integer.parseInt(s); i++){

           Knowledgepoint kul =  new Knowledgepoint()
                    .setGradeType(map.get(GRADE_TYPE.getName()+","+i).toString())
                    .setKdname(map.get(KDNAME.getName()+","+i).toString())
                    .setSubject(map.get(SUBJECT.getName()+","+i).toString())
                    .setStatu((int)Double.parseDouble(map.get(STATU.getName()+","+i).toString()));
           listKnowledgepoint.add(kul);
            System.out.println(kul);
        }
        //判断是否有相同的知识点
        for (int i = 0 ; i < kdnameAll.size(); i++){
            for (int j = 0 ; j < listKnowledgepoint.size() ; j++){
                if (kdnameAll.get(i).getKdname().equals(listKnowledgepoint.get(j).getKdname())){
                    System.out.println("重复知识点上传失败");
                    return new ResponseResult<Map<String, Object>>().setCode(400).setMessage("有重复的知识点，上传失败");

                }
            }
        }
        System.out.println("上传成功");
         uploadingService.insertKnowledges(listKnowledgepoint);
        //根据字段查询
        return new ResponseResult<Map<String, Object>>().setCode(400).setMessage("上传成功");
    }

    //显示知识点页面--分页
    @RequestMapping("/selectall")
    public ResponseResult<PageInfo<Knowledgepoint>> selectAll(@RequestParam(value = "pn",defaultValue = "1")Integer pn){
        PageHelper.startPage(pn,5);
        List<Knowledgepoint> knowledgepoints = uploadingService.selectAll();
        PageInfo<Knowledgepoint> page = new PageInfo<Knowledgepoint>(knowledgepoints,5);
        return new ResponseResult<PageInfo<Knowledgepoint>>().setCode(200).setMessage("ok").setData(page);
    }
}
